package web

import (
	"io"
	"mime/multipart"
	"os"
)

type FileUploader struct {
	FileField   string
	DstPathFunc func(fh *multipart.FileHeader) string
}

func (f *FileUploader) Handle() HandleFunc {
	return func(ctx *Context) {
		src, srcHeader, err := ctx.Req.FormFile(f.FileField)
		if err != nil {
			return
		}
		defer src.Close()

		dst, err := os.OpenFile(f.DstPathFunc(srcHeader), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o666)
		if err != nil {
			return
		}
		defer dst.Close()
		_, err = io.CopyBuffer(dst, src, nil)
		if err != nil {
			return
		}
		ctx.RespData = []byte("上传成功")
	}
}
